#include "user_adc.h"
#include "user_init.h"
#include "user_uart_interrupt.h"
extern measure_value MeasureData;
float clean_air_voc=0.4;
static uint32_t GetVREF1P2Sample_POLL(void)
{
	uint16_t ADCRdresult;
	uint8_t i=0;
	FL_RCC_SetADCPrescaler(FL_RCC_ADC_PSC_DIV8);
    FL_VREF_EnableVREFBuffer(VREF);
	FL_ADC_EnableSequencerChannel(ADC, FL_ADC_INTERNAL_VREF1P2);
	FL_ADC_ClearFlag_EndOfConversion(ADC);
	FL_ADC_Enable(ADC);   	 
	FL_ADC_EnableSWConversion(ADC);  
    
	while (FL_ADC_IsActiveFlag_EndOfConversion(ADC) == RESET)
	{
		if(i>=5)
		{
			break;
		}
		i++;
		DelayMs(1);
	}
	FL_ADC_ClearFlag_EndOfConversion(ADC);
	ADCRdresult =FL_ADC_ReadConversionData(ADC);
    FL_ADC_Disable(ADC);    
	FL_ADC_DisableSequencerChannel(ADC, FL_ADC_INTERNAL_VREF1P2);
    FL_VREF_DisableVREFBuffer(VREF);
    
  return ADCRdresult;
}
static uint32_t GetSingleChannelSample_POLL(uint32_t channel)
{
	uint16_t ADCRdresult;
	uint8_t i=0;
	FL_RCC_SetADCPrescaler(FL_RCC_ADC_PSC_DIV1);
	FL_ADC_EnableSequencerChannel(ADC, channel);
	FL_ADC_ClearFlag_EndOfConversion(ADC);
	FL_ADC_Enable(ADC);   	 
	FL_ADC_EnableSWConversion(ADC);  
    
	while (FL_ADC_IsActiveFlag_EndOfConversion(ADC) == RESET)
	{
		if(i>=5)
		{
			break;
		}
		i++;
		DelayMs(1);
	}
	FL_ADC_ClearFlag_EndOfConversion(ADC);
	ADCRdresult =FL_ADC_ReadConversionData(ADC);
    FL_ADC_Disable(ADC);    
	FL_ADC_DisableSequencerChannel(ADC, channel);
    
  return ADCRdresult;
}
uint32_t GetSingleChannelVoltage_POLL(uint32_t channel)
{
	uint32_t Get122VSample,GetChannelVoltage;
	uint64_t GetVSample;
	Get122VSample = GetVREF1P2Sample_POLL();
	
	GetVSample =GetSingleChannelSample_POLL(channel);
	GetChannelVoltage =  (GetVSample *3300*(ADC_VREF))/(Get122VSample*4095);
	
    
    return GetChannelVoltage;
}
void Get_Ordor_Data(void)
{
		float voc_temp=0;
		float voc_ratio=0;
		voc_temp = (float)(GetSingleChannelVoltage_POLL(FL_ADC_EXTERNAL_CH0))/1000;
		voc_ratio=(1/voc_temp-0.2)/(1/clean_air_voc-0.2);
		if(voc_ratio>1)
				voc_ratio = 1;
			else if(voc_ratio<=0)
				voc_ratio = 0.01;
		SysPrintf("voc_sample=%1.3f,voc_ratio=%1.3f\r\n",voc_temp,voc_ratio);
		MeasureData.VOC = (uint16_t)(voc_ratio*100.0);
}